package com.apes.auto.maintain.service;

import com.apes.auto.car.repository.CarTypeConfigurationRepository;
import com.apes.auto.maintain.model.LatestCarModel;
import com.apes.auto.maintain.model.MaintainPeriodApp;
import com.apes.auto.maintain.model.MaintainPeriodChange;
import com.apes.auto.maintain.model.PivotRule;
import com.apes.auto.maintain.repository.LatestCarModelRepository;
import com.apes.auto.maintain.repository.MaintainPeriodAppRepository;
import com.apes.auto.maintain.repository.MaintainPeriodChangeRepository;
import com.apes.auto.maintain.repository.PivotRuleRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.query.SqlService;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName LatestCarModelService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/8/8 17:59
 * @Version 1.0
 **/
@Service("latestCarModelService")
public class LatestCarModelService extends DomainService {
    @Autowired
    private LatestCarModelRepository carModelRepository;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private PivotRuleRepository pivotRuleRepository;
    @Autowired
    private MaintainPeriodChangeRepository maintainPeriodChangeRepository;
    @Autowired
    private CarTypeConfigurationRepository configurationRepository;
    @Autowired
    private MaintainPeriodAppRepository maintainPeriodAppRepository;

    @Autowired
    SqlService sqlService;

    public LatestCarModel save(SimpleRequest request) {
        LatestCarModel o = request.getO(LatestCarModel.class);
        return carModelRepository.save(o);
    }

    public String delete(SimpleRequest request) {
        LatestCarModel o = request.getO(LatestCarModel.class);
        carModelRepository.delete(o);
        return "删除成功";
    }

    /**
     * 执行 保养周期存储过程
     *
     * @return
     */
    public String callProcedure() {
        LocalDateTime localDateTime = LocalDateTime.now();
        String date = localDateTime.getYear() + "_" + localDateTime.getMonth().getValue() + "_" + localDateTime.getDayOfMonth();
        String tableName = "byzqb" + date;

        try {
            //执行前先备份一份往期数据
            Query nativeQuery = entityManager.createNativeQuery("CREATE TABLE" + tableName + " AS(SELECT * FROM byzqb WHERE byzqb.cxid IN (SELECT DISTINCT cxid FROM cxb_xding))");
            nativeQuery.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException("已存在表" + tableName + "无法备份保养周期总表");
        }


        //执行保养周期存储过程
        Query query = entityManager.createNativeQuery("{call gxbyzq()}");
        int i = query.executeUpdate();
        if (i <= 0) {
            throw new RuntimeException("执行失败");
        }

        // 运行完成后按cxb_xding中的车型ID，找出byzqb表中的新增修订部分命名为byzqb_change；
        query = entityManager.createNativeQuery("INSERT INTO byzqb_change SELECT * FROM byzqb WHERE cxid IN (SELECT DISTINCT cxid FROM cxb_xding)");
        query.executeUpdate();

        // 获得保养周期行转列规则
        List<PivotRule> rules = pivotRuleRepository.findAll();
        List<MaintainPeriodApp> maintainPeriodApps = new ArrayList<>();
        MaintainPeriodApp maintainPeriodApp = new MaintainPeriodApp();
        for (MaintainPeriodChange maintainPeriodChange : maintainPeriodChangeRepository.findAll()) {
            Map map = MapUtil.mapped(maintainPeriodChange);
            Map<String, Object> appMap = new HashMap<>();
            Map<String, List<PivotRule>> group = rules.stream().collect(Collectors.groupingBy(PivotRule::getPJMCID));
            for (Map.Entry<String, List<PivotRule>> entry : group.entrySet()) {
                entry.getValue().forEach(pivotRule -> {
                    appMap.put(pivotRule.getXTZD(), map.get(pivotRule.getBYZQBZD()));
                });
                appMap.put("PLID", entry.getValue().get(0).getPLID());
                appMap.put("PLMC", entry.getValue().get(0).getPJMC());
                appMap.put("PJMC", entry.getValue().get(0).getPJMC());
                appMap.put("PJMCID", entry.getValue().get(0).getPJMCID());
                appMap.put("SJPJMC", entry.getValue().get(0).getSJPJMC());

            }
            appMap.put("CXID", maintainPeriodChange.getCXID());
            appMap.put("PZCXMC", configurationRepository.findOne(maintainPeriodChange.getCXID()).getPZCXMC());
            maintainPeriodApp = MapUtil.getO(appMap, MaintainPeriodApp.class);
            maintainPeriodApp.setCP(maintainPeriodChange.getCP());
            maintainPeriodApp.setPP(maintainPeriodChange.getPP());
            maintainPeriodApp.setCX(maintainPeriodChange.getCX());
            maintainPeriodApps.add(maintainPeriodApp);
        }

        maintainPeriodAppRepository.save(maintainPeriodApps);
        //执行完后备份并清空过度表
        tableName = "byzqb_change" + date;

        try {
            query = entityManager.createNativeQuery("CREATE TABLE" + tableName + " AS(SELECT * FROM byzqb_change)");
            query.executeUpdate();
            maintainPeriodChangeRepository.deleteAll();
        } catch (Exception e) {
            throw new RuntimeException("已存在表" + tableName + "无法备份ERP保养周期表");
        }


        return "执行成功";
    }
}
